import Vue from "vue";
import VueRouter from "vue-router";

Vue.use(VueRouter);

const routes = [
  {
    path: "/home",
    component: Home,
    meta: { show: true },
  },
  {
    path: "/register",
    component: Register,
  },
  {
    path: "/login",
    component: Login,
  },
  {
    path: "/search/:keyword?",
    component: Search,
    meta: { show: true },
    name: "search",
  },
  {
    // 重定向到首页
    path: "*",
    redirect: "/home",
  },
];

//引入路由组件
import Home from "../views/Home/index";
import Login from "../views/Login/index";
import Register from "../views/Register/index";
import Search from "../views/Search/index";

// 保存原生push
let originPush = VueRouter.prototype.push;
let originReplace = VueRouter.prototype.replace;

// 重写push|replace 第一个参数告诉原来的push往哪里跳转，传递哪些参数 重写是因为编程式导航控制台会报警告错误
VueRouter.prototype.push = function (location, resoleve, reject) {
  if (resoleve && reject) {
    // call 和 apply 的异同  同：都可以调用函数并且篡改函数上下文一次  异：call传递参数用逗号隔开，apply传递参数用数组
    originPush.call(this, location, resoleve, reject);
  } else {
    originPush.call(
      this,
      location,
      () => {},
      () => {}
    );
  }
};

VueRouter.prototype.replace = function (location, resoleve, reject) {
  if (resoleve && reject) {
    // call 和 apply 的异同  同：都可以调用函数并且篡改函数上下文一次  异：call传递参数用逗号隔开，apply传递参数用数组
    originReplace.call(this, location, resoleve, reject);
  } else {
    originReplace.call(
      this,
      location,
      () => {},
      () => {}
    );
  }
};

const router = new VueRouter({
  routes,
});

export default router;
